在程式開發中,經常需要處理「一堆資料」。
例如:要同時管理多檔股票,光靠一個一個變數會很難維護。
今天我們要學會 集合 (Collection),並透過 List<T> 和 Dictionary<TKey, TValue> 來管理股票清單。
C# 的集合分成兩類:
ArrayList
List<T>
using System;
using System.Collections;
class Program
{
    static void Main()
    {
        ArrayList list = new ArrayList();
        list.Add("2330");
        list.Add(1265m); // 可以放不同型別
        foreach (var item in list)
        {
            Console.WriteLine(item);
        }
    }
}
問題:
ArrayList 允許不同型別混在一起,容易出錯。using System;
using System.Collections.Generic;
class Program
{
    static void Main()
    {
        List<string> symbols = new List<string>();
        symbols.Add("2330");
        symbols.Add("2303");
        foreach (string s in symbols)
        {
            Console.WriteLine(s);
        }
    }
}
好處:
string)ArrayList 更好List<T> 是動態陣列,可以隨時新增或移除元素。
List<string> stocks = new List<string>();
stocks.Add("2330");
stocks.Add("2303");
Console.WriteLine(stocks[0]);           // 2330
Console.WriteLine($"股票數量:{stocks.Count}");
常見操作:
Add() 新增Remove() 移除Count 取得數量[] 透過索引存取Dictionary<TKey, TValue> 是「鍵值對集合」,適合快速查找。
Dictionary<string, decimal> prices = new Dictionary<string, decimal>();
prices["2330"] = 1265m;
prices["2303"] = 45.7m;
Console.WriteLine(prices["2330"]); // 1265
常見操作:
Add(key, value) 新增ContainsKey(key) 判斷是否存在Remove(key) 移除簡單記法:
public class Stock
{
    public string Symbol { get; set; }
    public decimal Price { get; set; }
}
class Program
{
    static void Main()
    {
        // 用 List 管理股票
        List<Stock> stocks = new List<Stock>
        {
            new Stock { Symbol = "2330", Price = 1265m },
            new Stock { Symbol = "2303", Price = 45.7m }
        };
        foreach (Stock s in stocks)
        {
            Console.WriteLine($"{s.Symbol} 價格 {s.Price}");
        }
        // 用 Dictionary 快速查找股票
        Dictionary<string, Stock> stockDict = new Dictionary<string, Stock>();
        stockDict["2330"] = new Stock { Symbol = "2330", Price = 1265m };
        if (stockDict.ContainsKey("2330"))
        {
            Console.WriteLine($"2330 的價格是 {stockDict["2330"].Price}");
        }
    }
}
今天我們學會了:
List<T> 適合依序處理資料Dictionary<TKey, TValue> 適合快速查找資料List 存清單,Dictionary 查價格